if (!window.FLRT) FLRT = {
	lib: {
		text: {}
	},
	dialogs: {}
};

FLRT.debugging = false;

jQuery.extend({
	rand: function(min, max) {
	  return Math.floor(Math.random() * (max - min + 1)) + min;
	}
});

if (!Function.prototype.bind) { // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind
	Function.prototype.bind = function (oThis) {
		if (typeof this !== "function") // closest thing possible to the ECMAScript 5 internal IsCallable function
			throw new TypeError("Function.prototype.bind - what is trying to be fBound is not callable");
		var aArgs = Array.prototype.slice.call(arguments, 1),
			fToBind = this,
			fNOP = function () {},
			fBound = function () {
				return fToBind.apply(this instanceof fNOP ? this : oThis || window, aArgs.concat(Array.prototype.slice.call(arguments)));
			};
		fNOP.prototype = this.prototype;
		fBound.prototype = new fNOP();
		return fBound;
	};
}

Object.reset = function(object, key){
	if (key == null){
		for (var p in object) Object.reset(object, p);
		return object;
	}
	delete object[key];
	switch ($.type(object[key])){
		case 'object': object[key] = $.extend(true, {}, object[key]); break;
		case 'array': object[key] = $.extend(true, [], object[key]); break;
	}
	return object;

};

/***************************************/

/* Debugging utilites */

FLRT.log =       function(){ if (FLRT.debugging && console && console.log)   console.log.apply(console, arguments); };
FLRT.log.error = function(){ if (FLRT.debugging && console && console.error) console.error.apply(console, arguments); };
FLRT.log.warn =  function(){ if (FLRT.debugging && console && console.warn)  console.warn.apply(console, arguments); };
FLRT.log.info =  function(){ if (FLRT.debugging && console && console.info)  console.info.apply(console, arguments); };

FLRT.createLogMethod = function(name){
	var log =   function(){};
	log.error = function(){};
	log.warn =  function(){};
	log.info =  function(){};
	return log;
	var log =   function(str){ if (FLRT.debugging && console && console.log)   console.log('['+name+']: ' + str); };
	log.error = function(str){ if (FLRT.debugging && console && console.error) console.error('['+name+']: ' + str); };
	log.warn =  function(str){ if (FLRT.debugging && console && console.warn)  console.warn('['+name+']: ' + str); };
	log.info =  function(str){ if (FLRT.debugging && console && console.info)  console.info('['+name+']: ' + str); };
	return log;
};


/****/

FLRT.scrollToShow = function($element) {
	var $doc = $(document);
	var top = $element.offset().top;
	var dtop = $doc.scrollTop();

	if (top < dtop) {
		$doc.scrollTop(top);
	}
};

/* Localisation utility */
/**
 * @param key
 * @param val
 * @returns {*}
 * @deprecated You should now use LT.t.
 */
FLRT.t = function(key, val){
	if ($.type(key) == 'object') $.each(key, this.t.bind(this));
	else if (val) {
		if (this.lib.text[key]) {
			this.log.warn('FLRT.lib.text["' + key + '"] exists and is "' + this.lib.text[key] + '"! Replacing with "' + val + '".');
		}
		this.lib.text[key] = val;
	}
	else if (this.lib.text[key]) {
		return this.lib.text[key];
	}
	else {
        if (LT && LT.t) {
            console.warn('Function FLRT.t is deprecated. Use LT.t with arguments: ', arguments);
            return LT.t.apply(LT, arguments);
        }
        else {
            return key;
        }
	}
};


/* FLRT.Class.js */

/* Note: Both top and bottom minimal margins are set in css 'margin-bottom' property */

FLRT.Class = function(obj){
	var newClass = function(){
		Object.reset(this);
		var value = (this.init) ? this.init.apply(this, arguments) : this;
		this.init = null;
		return value;
	};

	$.extend(newClass.prototype, {
		_events: {},
		binds: function(){
			$.each(arguments, function(i, item){
				if (this[item]) this[item] = this[item].bind(this);
			}.bind(this));
		},
		addEvent: function(event, action){
			if (!this._events[event]) this._events[event] = [];
			this._events[event].push(action.bind(this));
		},
		fireEvent: function(event){
			if (this._events[event]) {
				$.each(this._events[event], function(i, item){
					item();
				});
			}
		},
		log: FLRT.log
	}, obj);
	return newClass;
};


/* Dialog */

FLRT.Dialog = new FLRT.Class({

	_settings : {
		/** @type {String} */
		id : undefined
		},
	init: function( content , settings ){
		this.binds('open', 'close');

		if ( settings ){
			$.extend( this._settings, settings );
			}
			
		this.content = content ? $(content) : $('<div></div>');

		// Modal dialog background
		this.bg = FLRT.Dialog.bg;
		// Dialog wrap
		this.element = $('<div>', {'class': 'modal-dialog'});
		if ( this._settings.id ){
			this.element.addClass( 'modal-dialog-id-' + this._settings.id );
			}
		// Close button
		this.element.append($('<a>', {'class': 'close modal-close'}));
		// Content
		this.element.append($(content));
		this.element.find('.close').click(this.close);
		//$.data(this.element[0], 'combobox', this);
		return this;
	},

	open: function(){
		if (this.active) return this;
		this.bg.show().appendTo($('body'));
		this.element.appendTo($('body'));
		FLRT.activeDialog = this;
		this.active = true;
		this.resizeWrap();
		this.fireEvent('open');
		return this;
	},

	/*close: function(){
		this.element.fadeOut(function(){
			this._close();
		}.bind(this));
		this.bg.fadeOut();
	},*/

	close: function(){
		if (!this.active) return this;
		this.element.detach(); // Remove dialog
		this.bg.detach(); // Remove background
		this.resetWrap(); // Reset document wrap to defult size
		FLRT.activeDialog = null;
		this.active = false;
		this.fireEvent('close');
		return this;
	},

	position: function(element){ // Centers dialog
		element = $(element || this.element);
		var win = $(window);
		win = {height: win.height(), width: win.width()};
		var hm = parseInt(element.css('margin-bottom'));
		var h = this.getHeight(element);
		if ((h + hm*2) > win.height) {
			element.css({'margin-top': hm, 'top': '0'});
		}
		else {
			element.css({'margin-top': -h/2, 'top': '50%'});
		}
		var wm = parseInt(element.css('margin-right'));
		var w = this.getWidth(element);
		if ((w + wm*2) > win.width) {
			element.css({'margin-left': wm, 'left': '0'});
		}
		else {
			element.css({'margin-left': -w/2, 'left': '50%'});
		}

		return this;
	},

	getHeight: function(element){ // Gets dialogs outer height
		element = $(element || this.element);
		if (this.active) {
			return element.outerHeight();
		} else {
			this.element.css('visibility', 'hidden').appendTo($('body'));
			var height = element.outerHeight();
			this.element.detach().css('visibility', 'visible');
			return height;
		}
	},

	getWidth: function(element){ // Gets dialogs outer height
		element = $(element || this.element);
		if (this.active) {
			return element.outerWidth();
		} else {
			this.element.css('visibility', 'hidden').appendTo($('body'));
			var width = element.outerWidth();
			this.element.detach().css('visibility', 'visible');
			return width;
		}
	},

	resizeWrap: function(){ // Resizes document wrap and modal background to prevent surplus scrolling
		// Height
		this.winHeight = $(window).height();
		this.winScrollTop = this.winScrollTop || $(window).scrollTop();
		var height = this.winHeight + this.winScrollTop;
		var dh = this.getHeight() + parseInt(this.element.css('margin-bottom'))*2;
		if (this.winHeight < dh) height = dh + this.winScrollTop;
		//Width
		var width = $(window).width();
		var dw = this.getWidth() + parseInt(this.element.css('margin-right'))*2;
		if (width < dw) width = dw;
		// Apply
		$('#wrap').css({
			'overflow': 'hidden',
			'height': height,
			'width': width,
			'margin-top': -this.winScrollTop
		});
		this.bg.css({
			'height': height,
			'width': width
		});
		this.position();
		$(window).scrollTop(0);
		return this;
	},

	resetWrap: function(){ // Resets document wrap size
		var $this = this;
		$('#wrap').css({
			'height': 'auto',
			'width': 'auto',
			'margin-top': '0'
		});
		setTimeout(function(){
			$(window).scrollTop($this.winScrollTop); // Resrore scroll position
			$this.winScrollTop = 0;
			$(window).resize();
			$('#wrap').css({
				'height': 'auto',
				'width': 'auto',
				'margin-top': '0'
			});
		},50);
	},

	focus: function(selector){ // Focus on form field
		$(this.element.find(selector || 'input[type=text], textarea').get(0)).focus();
		return this;
	},

	alert: function(content){ // Alert message and close dialog
		this.close();
		var d = new FLRT.Dialog($('<div>', {'class': 'alert'}).html(content));
		d.open();
		setTimeout(function(){
			d.element.fadeOut(function(){
				d.close();
			});
		}, 8000);
	},
	
	loading : function( state ){
		if ( ! this.submitButton ){
			this.submitButton = this.element.find( 'button[type=submit],.modal-dialog-submit-button' );
			this.submitButton.before( '<span class="modal-dialog-loader" />' );
			}
		if ( this.element.toggleClass( 'loading' , state ).hasClass( 'loading' ) ){
			this.submitButton.attr( 'disabled' , 'disabled' );
			}
		else{
			this.submitButton.removeAttr( 'disabled' );
			}
		}

});

FLRT.Dialog.bg = $('<div>').attr('class', 'modal-bg'); // Common modal Background
FLRT.Dialog.bg.click(function(e){ // Close dialog on background click
	e.stopPropagation();
	if (FLRT.activeDialog) FLRT.activeDialog.close();
});
$(window).resize(function(e){
	if (FLRT.activeDialog) FLRT.activeDialog.resizeWrap();
});
FLRT.UserRelations = (function(){
	var
		RELATION_TYPE_YES = 'yes',
		RELATION_TYPE_MAYBE = 'maybe',
		RELATION_TYPE_NO = 'no',
		_settings = {
			saveUrl : '/users/carousel'
			},
		/** 
		 * Public of UserRelations
		 */
		obj = {
			RELATION_TYPE_YES : RELATION_TYPE_YES,
			RELATION_TYPE_MAYBE : RELATION_TYPE_MAYBE,
			RELATION_TYPE_NO : RELATION_TYPE_NO,
			save : function( params ){
				var
					_params = {
						/** 
						 * Type of saved relation
						 * One of [yes,maybe,no]
						 * @type {String}
						 */
						type : undefined,
						/**
						 * Id of target user 
						 * @type {Number} */
						uid : undefined,
						success : function(){},
						complete : function(){},
						error : function(){}
						}
				params && $.extend( _params , params );
				$.request( {
					type : 'POST',
					quite : true,
					url : _settings.saveUrl,
					data : {
						uid : _params.uid,
						r_type : _params.type
						},
					success : _params.success,
					complete : _params.complete,
					error : _params.error
					} )
				}
			}
	return obj;
	})();

FLRT.UserBalloon = (function(){
	var
		/** @type {jQuery} */
		$balloon,
		/** @type {jQuery} */
		$balloonContent,
		_settings = {
			offsetLeft : 16,
			offsetTop : - 16,
			hideDelay : 500,
			showDelay : 200,
			activeClass : 'user-balloon-active',
			dataIdField : '__userBalloonId'
			},
		inactivePos = {
			left : -9000,
			top : -9000
			},
		/** 
		 * Global counter of all targets
		 * @type {Number}
		 */
		globalNum = 0,
		/** @type {jQuery} */
		$target,
		activeTargetNum,
		/** 
		 * Data of active user
		 * @type {Object}
		 */
		user = {
			/** @type {Number} */
			id : undefined,
			/** @type {String} */
			name : undefined,
			/** @type {Boolean} */
			profileTargetBlank : false,
			/** @type {Boolean} */
			carousel : false
			},
		/** @type {Boolean} */
		isActive = false,
		/** @type {Number} */
		hideTimer,
		/** @type {Number} */
		showTimer,
		init = function(){
			$(document.body)
				.delegate( 'img.user-avatar' , 'mouseover' , function(){
					activeTargetNum = getTargetId( $( this ) );
					showBalloon( $( this ) );
					} )
				.delegate( 'img.user-avatar' , 'mouseout' , function(){
					activeTargetNum = NaN;
					} );
			},
		/** 
		 * Sends any free event(s) to all listeners
		 */
		triggerEvent = function( event, eventData ){
			$( document ).triggerHandler( event, [ eventData ] );
			},
		obj = {
			EVENT_CLICK_CAROUSEL : 'userBalloon_click_carousel',  
			/** 
			 * Binds any free event(s) to instance
			 * Using jQuery's <code>bind</code> function syntax
			 */
			bind : function(){
				var $container = $( document );
				$container.bind.apply( $container, arguments );
				},
			/** 
			 * Unbinds any free event(s) to instance
			 * Using jQuery's <code>unbind</code> function syntax
			 */
			unbind : function(){
				var $container = $( document );
				$container.unbind.apply( $container, arguments );
				}
			};
				
		function fillBalloonForUser( /* user */u ){
			if ( ! $balloonContent || ! u || ! u.id ){
				return;
				}
			var
				html = [];
			html.push(
				'<ul id="user-balloon-links">',
					u.carousel
						? h(
							'<li>',
								'<a href="/users/view/' , u.id , '" id="user-balloon-link-carousel">',
									FLRT.t( 'userBalloonCarousel') , 
								'</a>',
							'</li>'
							)
						: '',
					'<li>',
						'<a href="/users/view/' , u.id , '" id="user-balloon-link-chat">' ,
							LT.t('userBalloonChat') ,
						'</a>',
					'<li>',
						'<a href="/users/view/' , u.id , '" id="user-balloon-link-profile"' ,
							u.profileTargetBlank
								? ' target="_blank"'
								: ''
							, '>',
							LT.t('userBalloonProfile') ,
						'</a>',
//					'<li>',
//						'<a href="/users/view/' , u.id , '" id="user-balloon-link-exchange">',
//							FLRT.t( 'userBalloonExchange') ,
//						'</a>',
//					'</li>',
				'</ul>'
				)
			$balloonContent.html( html.join('') );
			}
		/** 
		 * @param {jQuery} target to place balloon near
		 */
		function placeBalloon( $target ){
			var
				offset = $target.offset(),
				tw = $target.outerWidth(),
				th = $target.outerHeight(),
				bw = $balloon.outerWidth(),
				bh = $balloon.outerHeight();
			$balloon.css( {
				left : offset.left + tw + _settings.offsetLeft,
				top : offset.top - bh + _settings.offsetTop
				} );
			}
		function hideBalloon( force ){
			var hide = function(){
				$balloon
					.removeClass( _settings.activeClass )
					.css( inactivePos );
				}
			if ( hideTimer ){
				clearTimeout( hideTimer );
				hideTimer = undefined;
				}
			isActive = false;
			if ( force === true ){
				hide();
				}
			else{
				hideTimer = setTimeout(function(){
					if ( ! isActive ){
						hide();
						}
					}, _settings.hideDelay );
				}
			}
			
		function onMouseOutOfTarget(){
			activeTargetNum = NaN;
			hideBalloon();
			}
			
		/** 
		 * @param {jQuery}
		 */
		function getTargetId( $t ){
			if ( ! $t || ! $t[0] ){
				return NaN;
				}
			var 
				tid = $.data($t[0] , _settings.dataIdField );
			if ( isNaN ( + tid ) ){
				$.data( $t[0] , _settings.dataIdField , tid = globalNum ++ );
				}
			return tid;
			}
		
		/** 
		 * @param {jQuery} Potential target
		 */
		function showBalloon( $t ){
			if ( showTimer ){
				clearTimeout( showTimer );
				showTimer = undefined;
				}
			showTimer = setTimeout(function(){
				if ( getTargetId( $t ) != activeTargetNum ){
					return;
					}
				$target = $t;
				if ( ! $balloon || ! $balloon.length ){
					/* Creating balloon at first time */
					$balloon = $( [
						'<div id="user-balloon">',
							'<div id="user-balloon-core">',
								'<div id="user-balloon-content" />',
							'</div>',
							'<span class="user-balloon-cloud" id="user-balloon-cloud-1"/>',
							'<span class="user-balloon-cloud" id="user-balloon-cloud-2" />',
						'</div>'].join('') )
						.hover(
							function(){
								isActive = true
								},
							hideBalloon)
						.delegate( '#user-balloon-link-chat' , 'click', function(){
							_openChat( 1 );
							hideBalloon()
							return false;
							} )
						.delegate( '#user-balloon-link-carousel' , 'click', function(){
							triggerEvent( obj.EVENT_CLICK_CAROUSEL, {
								target : $target,
								user : user
								} )
							hideBalloon( true );
							return false;
							} )
						.appendTo(document.body);
					$balloonContent = $balloon.find( '#user-balloon-content' );
					}
				isActive = true;
				user.id = $target.searchInClass( 'user-avatar-id-' );
				user.profileTargetBlank = $target.searchInClass( 'user-avatar-profileTargetBlank-' );
				user.carousel = $target.searchInClass( 'user-avatar-carousel-' );
				fillBalloonForUser( user );
				setTimeout(function(){
					$balloon.addClass( _settings.activeClass );
					}, 10)
				placeBalloon( $target );
				$target
					.unbind( 'mouseout' , hideBalloon )
					.bind( 'mouseout' , hideBalloon );
				}, _settings.showDelay);
			}
		/** 
		 * Opens chat with active user in given form
		 * @param {Number} type @default 1
		 */
		function _openChat(  ){
			if ( ! user.id || ! window.openChat ){
				/* Cannot continue without correct active user */
				return false;
				}
			window.openChat( user.id );
			}
		
	$( init );
	
	return obj;
	})();
	
FLRT.SEX_F = 0;
FLRT.SEX_M = 1;
FLRT.SEX_SEARCH_F = 1;
FLRT.SEX_SEARCH_M = 2;
FLRT.LOOKING_FOR_PAIR = 2;
FLRT.LIKE_FORME = 1;
FLRT.LIKE_MUTUAL = 2;
FLRT.LIKE_MY = 3;

;(function(){
	var
		/** @type {jQuery} */
		$overlay,
		/** @type {jQuery} */
		$dialog,
		/** @type {jQuery} */
		$text,
		/** @type {jQuery} */
		$subtext,
		/** @type {jQuery} */
		$yes,
		/** @type {jQuery} */
		$no,
		/** @type {jQuery} */
		$close,
		isShow = false;
	function show(){
		if ( isShow ){
			return false;
			}
		$overlay.addClass( 'flrt-overlay-active' );
		$dialog
			.addClass( 'flrt-confirm-deactivated' )
			.fadeTo( 0 , 0 )
			.show();
		place();
		$dialog
			.fadeTo( 50 , 1 , function(){
				$dialog.removeClass( 'flrt-confirm-deactivated' )
				} );
		
		$( document ).bind( 'keyup' , onKeyPress );
		isShow = true;
		}	
	function hide(){
		if ( ! isShow ){
			return false;
			}
		$overlay.removeClass( 'flrt-overlay-active' );
		$dialog.hide();
		$( document ).unbind( 'keyup' , onKeyPress );
		isShow = false;
		}
		
	function place(){
		var
			dw = $dialog.outerWidth(),
			dh = $dialog.outerHeight();
		$dialog.css({
			marginTop : Math.round( -dh / 2 ),
			marginLeft : Math.round( -dw / 2 )
			})
		}
		
	function onKeyPress(/* Event */e){
		if ( e.keyCode == 27 ){
			hide();
			}
		}
	FLRT.Confirm = function( settings ){
		var
			_settings = {
				/** @type {String} */
				text           : 'Are you sure?',
				/** @type {String} */
				subtext        : undefined,
				/** @type {String} */
				yesCaption     : 'Yes',
				/** @type {String} */
				noCaption      : 'Cancel',
				onYes          : function(){},
				onNo           : function(){}
				};
		settings && $.extend( _settings , settings );
		if ( ! $dialog ){
			/* Init creating dialog */
			$dialog = $( j( 
				'<div id="flrt-confirm">',
					'<h2 id="flrt-confirm-text" />',
					'<div id="flrt-confirm-subtext" class="hidden"></div>',
					'<div id="flrt-confirm-submit-wrap">',
						'<span id="flrt-confirm-yes" />',
						'<span id="flrt-confirm-no" class="x-link" />',
					'</div>',
					'<span id="flrt-confirm-close" />',
				'</div>'
				) )
				.hide()
				.appendTo( document.body );
			$text = $dialog.find( '#flrt-confirm-text' );
			$subtext = $dialog.find( '#flrt-confirm-subtext' );
			$yes = $dialog.find( '#flrt-confirm-yes' )
			$no = $dialog.find( '#flrt-confirm-no' );
			$close = $dialog.find( '#flrt-confirm-close' ).click( hide )
			$overlay = $( '<div id="flrt-confirm-overlay" />' )
				.click( hide )
				.appendTo( document.body );
				
			}
			
		$text.html( _settings.text )
		$subtext.html( _settings.subtext || '' ).toggleClass( 'hidden' ,  ! _settings.subtext );
		$yes
			.unbind( 'click' )
			.bind( 'click' , function(){
				hide();
				_settings.onYes();
				})
			.html( _settings.yesCaption );
			
		if ( _settings.noCaption ){
			$no
				.unbind( 'click' )
				.bind( 'click' , function(){
					hide();
					_settings.onNo();
					})
				.html( _settings.noCaption );
			}
		else{
			$no.hide();
			}
			
		show();
		}
	})();
	
FLRT.UserIncognito = (function(){
	var EVENT_SAVE = 'saveIncognito';
	function addListener(){
		$( document ).bind.apply( $( document ) , arguments );
		}
	function removeListener(){
		$( document ).unbind.apply( $( document ) , arguments );
		}
	function triggerEvent( event , eventData ){
		$( document ).triggerHandler( event , [ eventData ] );
		}
	return {
		save : function( value , options ){
			if ( $.isFunction( value ) ){
				/* If single function argument given we think this is save listener */
				addListener( EVENT_SAVE , value );
				return;
				}
			var
				_options = {
					success  : function(){},
					complete : function(){} 
					}
			options && $.extend( _options , options );
			$.request({
				quite    : true,
				type     : 'POST',
				url      : '/users/UpdateIncognito',
				data     : {
					'hide_images' : value ? 1 : 0
					},
				success  : function( res ){
					_options.success();
					triggerEvent( EVENT_SAVE , $.extend( { 
						on : ! ! value 
						} , res ) );
					},
				complete : _options.complete 
				})
			}
		
		}
	})();

/* Checking number of site instances via localStorage */
;(function( $ ){
	
	/* XXX Temporarily disabled */
	return;
	
	
	if ( ! $ || ! $.storage ){
		return;
		}
	var
		/** 
		 * Name of field uses to store tab info
		 * @type {String}
		 */
		field = 'siteInstances',
		/** 
		 * Interval to check tabs current number
		 * @type {Number}
		 */
		tickInterval = 10000,
		ticker,
		/** 
		 * This tab id
		 * @type {Number}
		 */
		iid,
		/** 
		 * Max number of active tabs.
		 * At excess will be shown warn message
		 * @type {Number}
		 */
		warnActiveNum = 5,
		/** 
		 * Flag means if warn message is shown or not
		 * @type {Boolean}
		 */
		isWarn = false,
		/** 
		 * Warn message container
		 * @type {jQuery}
		 */
		$warn,
		/** 
		 * Shows or hides (related to given flag value) warn message
		 */
		warn = function( state ){
			if ( ! ! state ==  isWarn ){
				return;
				}
			if ( state ){
				/* Showing warn message */
				if ( ! $warn ){
					$warn = $( h( 
						'<div id="global-warn">' , 
							FLRT.t( 'warnTooManyTabs' ), 
						'</div>' ) )
						.hide()
						.prependTo( document.body );
					}
				$warn.slideDown( 500 , function(){
					$( window ).resize();
					} );
				}
			else{
				/* Hiding warn message */
				$warn.slideUp( 500 );
				}
			isWarn = ! ! state;
			},
		/** 
		 * Checks current active tabs number and updates info about current tab
		 */
		check = function(){
			var
				now = ( new Date ).getTime(),
				minTime =  now - tickInterval - 500, 
				/** @type {Object} */
				v = $.storage.get( field ) || {},
				activeNum = 0,
				n = 1;
			while ( ! iid ){
				if ( ! v[ n ] ){
					iid = n;
					}
				n ++
				}
			for ( vn in v ){
				if ( ! v.hasOwnProperty( vn ) ){
					continue;
					}
				if ( Number( v[ vn ] ) < minTime ){
					delete v[ vn ];
					}
				else if ( vn != iid ){
					activeNum ++;
					}
				}
			v[ iid ] = now;
			activeNum ++;
			$.storage.set( field , v );
			warn( activeNum >= warnActiveNum );
			return check;
			};
	
	/* Unsetting this tab info when unload */ 
	
	$( window ).unload( function(){
		var 
			v = $.storage.get( field ) || {};
		ticker && clearInterval( ticker );
		if ( iid && v[ iid ] ){
			delete v[ iid ];
			$.storage.set( field , v );
			}
		} );
		
	$(function(){
		/* Waiting some time to let page elements load and make warn message appears more prominent */
		setTimeout(function(){
			ticker = setInterval( check() , tickInterval );	
			},300)
		});
	})( window.jQuery );
	
	
FLRT.dispatcher = $.eventDriven({
	events : {
		USER_IGNORE          : 'userIgnore',
		USER_ADD_TO_FAVORITE : 'userAddToFavorite'
		},
	trigger : function(){
		var $this = $( this );
		$this.trigger.apply( $this, arguments );
		return this;
		}
	});
	

FLRT.actionSelector = function( options ){
	var
		/** @type {jQuery} */
		$container,
		items = [],
		isOpen = false;
		itemTemplates = {
			favorite : {
				id : 'favorite',
				title : LT.text.usersAddToFavorite
				},
			unfavorite : {
				id : 'unfavorite',
				title : LT.text.usersRemoveFromFavorite
				},
			block : {
				id : 'block',
				title : LT.text.actionBlock
				},
			present : {
				id : 'present',
				title : LT.t('sendGiftDialogSubmit')
				},
			complain : {
				id : 'complain',
				title : LT.text.chatComplain
				},
			filter : {
				id : 'filter',
				title : LT.t('messageFilterTitle')
				}
			},
		Item = function( itemData ){
			var
				instance = {
					id : undefined,
					title : undefined
					};
			if ( ! $.isPlainObject( itemData ) ){
				if ( itemTemplates[ itemData ] ){
					itemData = $.extend( {} , itemTemplates[ itemData ] );
					}
				else{
					itemData = {	
						id : itemData.toString,
						title : itemData.toString()
						}
					}
				}
			itemData && $.extend( instance, itemData );
			return instance;
			},
		instance = $.eventDriven({
			/** 
			 * @param {Array}
			 */
			setItems : function( newItems ){
				items = [];
				$.each( newItems, function(){
					items.push( Item( this ) );
					});
				render();
				return this;
				},
			appendTo : function( parent ){
				$container.appendTo( parent );
				return this;
				}
			});
			
	function render(){
		var html = [];
		$container.toggleClass( 'user-action-selector--s--empty', ! items.length );
		if ( ! items.length ){
			$container.empty();
			return;
			}
		html.push(
			'<ul class="n-nav-user-list">',
				'<li class="first-item">',
					'<a href="javascript:void(0)" class="top-invite user-action" data-action="' , items[ 0 ].id , '">',
						'<span class="mes-icon-' , items[ 0 ].id  , '">' , items[ 0 ].title, '</span>',
					'</a>',
				'</li>',
				items.length > 1
					? j( '<li class="last-item current js-profile-select-options"><a href="#" class="user-action-or"><span class="mes-icon-or">&nbsp;</span></a></li>' )
					: '',
			'</ul>'
			);
		if ( items.length > 1 ){
			html.push(
				'<div class="mes-user-command hidden">',
					'<ul>');
			for (var i = 1, l = items.length; i < l; i++) {
				html.push( 
					'<li class="mess-to-' , items[ i ].id , '">',
						'<a href="#" class="user-action" data-action="' , items[ i ].id , '"><span>' , items[ i ].title , '</span></a>',
					'</li>');
				
				}
			html.push(
					'</ul>',
				'</div>');
			}
		$container.html( html.join( '' ) );
		}
		
	$container = $( '<div class="user-action-selector" />' )
		.on( 'click', '.user-action-or', function(){
			toggle();
			return false;
			} )
		.on( 'click', '.user-action', function(){
			var action = $( this ).data( 'action' );
			$( instance ).trigger( 'select' );
			$( instance ).trigger( j( 'select:', action ) );
			close();
			return false;
			} )
		
	function open(){
		if ( isOpen ){
			return false;
			}
		$container.addClass( 'user-action-selector--s--open' );
		$( document.body ).on( 'click.userActionSelectorEvent', function( /* Event */e){
			if ( ! $( e.target ).is( '.user-action-selector, .user-action-selector *' ) ){
				close();
				}
			} );
		isOpen = true;
		}
		
	function close(){
		if ( ! isOpen ){
			return false;
			}
		$container.removeClass( 'user-action-selector--s--open' );
		$( document.body ).off( '.userActionSelectorEvent' );
		isOpen = false;
		}
		
	function toggle(){
		if ( isOpen ){
			close()
			}
		else{
			open();
			}
		}
	if ( options && options.items ){
		instance.setItems( options.items );
		}
	return instance;
	};
